package com.atguigu.jxc.service.impl;

import com.atguigu.jxc.dao.SupplierManageDao;
import com.atguigu.jxc.domain.ErrorCode;
import com.atguigu.jxc.domain.ServiceVO;
import com.atguigu.jxc.domain.SuccessCode;
import com.atguigu.jxc.entity.Goods;
import com.atguigu.jxc.entity.Log;
import com.atguigu.jxc.entity.Supplier;
import com.atguigu.jxc.service.LogService;
import com.atguigu.jxc.service.SupplierManageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SupplierManageServiceImpl implements SupplierManageService {

    @Autowired
    SupplierManageDao supplierManageDao;
    @Autowired
    LogService logService;

    @Override
    public Map<String, Object> pageSupplierList(Integer page, Integer rows, String supplierName) {
        Map<String,Object> map = new HashMap<>();

        page = page == 0 ? 1 : page;
        int offSet = (page - 1) * rows;

        List<Goods> list = supplierManageDao.pageSupplierListOrName(offSet,rows,supplierName);

        logService.save(new Log(Log.SELECT_ACTION,"分页查询供应商信息"));

        map.put("total", supplierManageDao.getSupplierCount(supplierName));
        map.put("rows", list);

        return map;
    }

    //添加或修改供应商
    @Override
    public ServiceVO save(Supplier supplier) {
        // 供应商ID为空时，说明是新增操作，需要先判断供应商名称是否存在
        if(supplier.getSupplierId() == null){

            Supplier supplierByName = supplierManageDao.findSupplierByName(supplier.getSupplierName());

            if (supplierByName != null) {
                return new ServiceVO(ErrorCode.SUPPLIER_EXIST_CODE, ErrorCode.SUPPLIER_EXIST_MESS);
            }

            supplierManageDao.addSupplier(supplier);
            logService.save(new Log(Log.INSERT_ACTION,"添加供应商:"+supplier.getSupplierName()));

        } else {

            supplierManageDao.updateUser(supplier);
            logService.save(new Log(Log.UPDATE_ACTION,"修改供应商:"+supplier.getSupplierName()));

        }

        return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }

    //删除供应商
    @Override
    public ServiceVO deleteSupplier(String ids) {
        logService.save(new Log(Log.DELETE_ACTION,"删除供应商:"+ids));
        String[] strings = ids.split(",");
        List<String> list = new ArrayList<>();

        for (String string : strings) {
            list.add(string);
        }
        supplierManageDao.deleteSuppliers(list);

        return new ServiceVO<>(SuccessCode.SUCCESS_CODE, SuccessCode.SUCCESS_MESS);
    }
}
